package com.jnr.hb.user;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.jnr.hb.MainActivity;
import com.jnr.hb.R;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

/**
 * 用户登录类
 * @author：景辉
 * created at 2016/12/27 0027 下午 4:57
 */
public class UserActivity extends AppCompatActivity {

    private EditText mUserName;
    private EditText mUserPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);
        //第一：默认初始化
        Bmob.initialize(this, "59bca982a33f85d9f5f89da9b2d95304");
        initView();
    }

    private void initView() {
        mUserName = (EditText) findViewById(R.id.userName);
        mUserPassword = (EditText) findViewById(R.id.userPassword);
    }

    //登录
    public void loginUserStart(View view){
        String name = mUserName.getText().toString().trim();
        String password = mUserPassword.getText().toString().trim();
        BmobUser person = new BmobUser ();
        if (name.equals("")||password.equals("")){
            Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
        }else {
            person.setUsername(name);
            person.setPassword(password);
            person.login(new SaveListener<BmobUser>() {
                @Override
                public void done(BmobUser bmobUser, BmobException e) {
                    if(e==null){
                        Toast.makeText(UserActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(UserActivity.this, MainActivity.class));
                        //通过BmobUser user = BmobUser.getCurrentUser()获取登录成功后的本地用户信息
                        //如果是自定义用户对象MyUser，可通过MyUser user = BmobUser.getCurrentUser(MyUser.class)获取自定义用户信息
                    }else{
                        Toast.makeText(UserActivity.this, "登录失败，请注册", Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(UserActivity.this,RegisterActivity.class));
                    }
                }
            });
        }
    }

    //注册
    public void registerUserStart(View view){
        startActivity(new Intent(UserActivity.this,RegisterActivity.class));
    }
}
